//
//  ZZCComposeViewController.swift
//  weibo
//
//  Created by zhangzuchao on 2017/4/5.
//  Copyright © 2017年 zhangZuChao. All rights reserved.
//

import UIKit
import SVProgressHUD
import SnapKit

//发微博的控制器
class ZZCComposeViewController: UIViewController {
    
    //   懒加载控件 导航控制器中间的富文本
    fileprivate lazy var titleLabel: UILabel = {
        let label = UILabel(fontSize: 17, textColor: UIColor.darkGray, text: "")
        if let name = ZZCUserAccountViewModel.sharedViewModel.userAccount?.name {
            let message = "发微博\n" + name
            
            //  获取名字的范围
            let range = (message as NSString).range(of: name)
            
            //  创建富文本
            let attributedStr: NSMutableAttributedString = NSMutableAttributedString(string: message)
            
            //  设置name文字的颜色和字体大小
            attributedStr.addAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 12), NSForegroundColorAttributeName: UIColor.orange], range: range)
            
            //  需要设置富文本
            label.attributedText = attributedStr
            
            //  多行显示
            label.numberOfLines = 0
            
            //  居中显示
            label.textAlignment = .center
            
        } else {
            //  没有登录
            label.text = "发微博"
        }
        label.sizeToFit()
        return label
    }()
    
    //  发送按钮
    fileprivate lazy var sendButton: UIButton = {
        let button = UIButton()
    
        //  添加点击事件
        button.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        
        //  设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        //  设置文字
        button.setTitle("发送", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.darkGray, for: .disabled)
        //  设置字体大小
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        //  设置大小
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    //  懒加载输入框 textView
    fileprivate lazy var textView: ZZCTextView = {
        let textView = ZZCTextView()
        
        //  不显示键盘上面那个输入提示
        textView.autocorrectionType = .no
        textView.delegate = self
        textView.placeHolder = "丑八怪 能否别把灯打开 我要的爱 出没在漆黑一片的舞台"
        textView.font = UIFont.systemFont(ofSize: 14)
        textView.textColor = UIColor.darkGray
        //  垂直方向可以拖动
        textView.alwaysBounceVertical = true
        return textView
    }()
    
    //   toolbar
    fileprivate lazy var toolBar: ZZCComposeToolBar = ZZCComposeToolBar()
    
    //  配图
    fileprivate lazy var pictureView: ZZCComposePictureView = {
        let collectionView = ZZCComposePictureView()
        return collectionView
    }()
    
    //表情键盘
 
    fileprivate lazy var emoticonKeyBoard: ZZCEmoticonKeyBoard = {
        let keyBoard = ZZCEmoticonKeyBoard()
        keyBoard.size = CGSize(width: self.textView.width, height: 226)
        return keyBoard
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    
    private func setupUI() {
        view.backgroundColor = UIColor.white
        
        //  监听键盘frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardFrameChangeAction(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //  监听表情按钮点击的通知
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedEmoticonButtonAction(noti:)), name: NSNotification.Name(DidSelectedEmoitconButtonNoti), object: nil)
        
        //  监听删除表情的通知
        NotificationCenter.default.addObserver(self, selector: #selector(didSelectedDeleteEmotionAction), name: NSNotification.Name(DidSelectedDeleteEmoticonNoti), object: nil)

        
         setupNavUI()
        
        view.addSubview(textView)
        
        //添加配图
        textView.addSubview(pictureView)
        view.addSubview(toolBar)
        
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        toolBar.snp.makeConstraints { (make) in
            make.bottom.leading.trailing.equalTo(self.view)
            make.height.equalTo(35)
        }
        
        pictureView.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-2 * HomeCellMargin)
            make.height.equalTo(textView.snp.width).offset(-2 * HomeCellMargin)
        }
        
        //  toolBar的回调闭包
        toolBar.buttonActionClosure = {[weak self] (type: ZZCComposeToolBarButtonType)->() in
            switch type {
            case .picture:
//                print("图片")
                //  图片浏览器
                self?.didSelectedPicture()
            case .mention:
                print("@")
            case .trend:
                print("#")
            case .emoticon:
//                print("表情")
                //  加载自定义表情
                self?.didSelectedEmotion()
            case .add:
                print("加号")
                
            }
        }
        //  设置添加图片的闭包
        pictureView.addPictureClosure = { [weak self] in
            self?.didSelectedPicture()
        }
    }
    
    //  添加导航栏视图
    fileprivate func setupNavUI() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.titleView = titleLabel
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //  默认右侧按钮不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
    }
    
    //   取消按钮点击
    @objc private func cancelAction() {
        //  结束编辑失去第一响应者
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    //   点击删除表情按钮的通知
    @objc private func didSelectedDeleteEmotionAction() {
        //  回删内容
        textView.deleteBackward()
    }

    
    //  发送微博  上传网络
    @objc private func sendAction() {
        //  获取令牌
        let accessToken = ZZCUserAccountViewModel.sharedViewModel.accessToken!
        //  微博内容
        let content = textView.text!
        
        //显示正在发送
        SVProgressHUD.show()
        
        if pictureView.images.count > 0 {
            let image = pictureView.images.first!
            
            //  带有图片的微博
            ZZCNetworkTools.shareTools.sendWeiboMessage(accessToken: accessToken, status: content, pic: image, finishCallBack: { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                } else {
                    SVProgressHUD.showSuccess(withStatus:"发送成功")
                }
            })
        } else {
            
            //  发送文字微博
            ZZCNetworkTools.shareTools.sendWeiboMessage(accessToken: accessToken, status: content) { (response, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发送失败")
                } else {
                    SVProgressHUD.showSuccess(withStatus:"发送成功")
                }
            }
        }
        
        
        
    }
    
    //   监听键盘的frame的改变
    @objc private func keyBoardFrameChangeAction(noti: Notification) {
        let userinfo = noti.userInfo!
        //  获取键盘的frame
        let keyboardFrame = userinfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        //  获取键盘的动画时长
        let duration = userinfo[UIKeyboardAnimationDurationUserInfoKey] as! Double
        
        //  修改toolbar底部约束
        toolBar.snp.updateConstraints { (make) in
            
        //  计算toolbar距离底部的间距-(ScreenHeight - keyboardFrame.origin.y)
        make.bottom.equalTo(self.view).offset(-(ScreenHeight - keyboardFrame.origin.y))
        }
        //  添加约束动画
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }
    
    //  点击表情按钮的监听方法
    @objc private func didSelectedEmoticonButtonAction(noti: Notification) {
        //  获取点击的表情模型
        let emoticon = noti.object as! ZZCEmoticon
        //  插入表情富文本
        textView.insertEmoticon(emoticon: emoticon)
        
        //  保存点击的表情模型
        ZZCEmoticonTools.sharedTools.saveRecentEmoticonArray(emoticon: emoticon)
        
        //  刷新最新表情的这组数据
        emoticonKeyBoard.reloadRecentData()
    }

 }

//  点击发图片的事件 使用UIImagePickerController获取图库图片
extension ZZCComposeViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  
    
    //  点击表情处理的逻辑
    fileprivate func didSelectedEmotion() {
        //  完成系统键盘和表情键盘的切换
        //  设置指示视图
        //        textView.inputAccessoryView
        if textView.inputView == nil {
            //  由系统键盘进入表情键盘
            //  输入视图
            textView.inputView = emoticonKeyBoard
            //
            toolBar.switchEmoticonIcon(isEmoticon: true)
        } else {
            //  由表情键盘进入系统键盘
            textView.inputView = nil
            toolBar.switchEmoticonIcon(isEmoticon: false)
        }
        
        //  设置成为第一响应者
        textView.becomeFirstResponder()
        //  重新加载输入视图
        textView.reloadInputViews()
        
    }
    
    
    
    //  点击图片处理的逻辑
    fileprivate func didSelectedPicture() {
        //   访问相机和相册需要开启权限 见截图
        let imagePictureCtr = UIImagePickerController()
        //  获取图片需要设置代理
        imagePictureCtr.delegate = self
        
        //  判断来源, 一定要要上判断
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            //  真机运行使用相机
            imagePictureCtr.sourceType = .camera
        } else {
            //  模拟器运行使用图库
            imagePictureCtr.sourceType = .photoLibrary
        }
 
        self.present(imagePictureCtr, animated: true, completion: nil)
    }
    
 
    //  实现代理方法UIImagePickerController
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        //  获取原始图片
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage
        
        //  根据指定的宽度获取压缩后的图片
        let currentImage = scaleImage(scaleWidth: 200, image: image)
        
        //  dismis
        picker.dismiss(animated: true, completion: nil)
        
        //  添加显示的图片
        pictureView.addImage(image: currentImage)
    }
    
    //  根据指定压缩后的宽度计算图片压缩后的大小
    fileprivate func scaleImage(scaleWidth: CGFloat, image: UIImage) -> UIImage {
        //  根据压缩后的宽度计算压缩后的高度  比如 400, 400  200  200
        let scaleHeight = scaleWidth / image.size.width * image.size.height
        //  压缩后大小
        let scaleSize = CGSize(width: scaleWidth, height: scaleHeight)
        //  开启图片上下文
        UIGraphicsBeginImageContext(scaleSize)
        //  把图片压缩到指定区域内
        image.draw(in: CGRect(origin: CGPoint.zero, size: scaleSize))
        //  从图片上下文中获取图片
        let currentImage = UIGraphicsGetImageFromCurrentImageContext()
        //  关闭图片上下文
        UIGraphicsEndImageContext()
        return currentImage!
        
        
    }

}


    //  MARK: ---UITextViewDelegate
extension ZZCComposeViewController: UITextViewDelegate    {
        func textViewDidChange(_ textView: UITextView) {
            //  根据文本框是否内容判断按钮是否可用
            navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
        }
        //  将要拖拽
        func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
            //  键盘失去第一响应者
            self.view.endEditing(true)
        }
    }

 


